package com.btcode.web.core.server;

import com.btcode.common.ExecuteTimeUtil;
import com.btcode.common.MyLog;
import com.btcode.common.PropertiesUnit;
import com.btcode.log.ILog;
import com.btcode.web.core.unit.URLUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;

/**
 * 继承jetty的server类，为了拦截所有的请求，做日志，并给错误地址已友好提示
 *
 * @author gislin
 */
public class WebServer extends org.eclipse.jetty.server.Server {

    ILog log;

    public WebServer(int port) {
        super(port);
        log = MyLog.getInstance().getLogger(getClass());
    }

    @Override
    public void handle(HttpChannel channel) throws IOException, ServletException {

        ExecuteTimeUtil executeTime = new ExecuteTimeUtil();

        String target = channel.getRequest().getPathInfo();
        Request request = channel.getRequest();
        Response response = channel.getResponse();
        String ip=URLUtil.getIpAddr(request);

        log.info("请求地址：" + target+" ;请求IP:"+ip);

        super.handle(channel);

        log.info(target + ",总处理耗时：" + executeTime.getLastDiffInSecond() + "s"+" ;请求IP:"+ip);

        if (!request.isHandled() && !response.isCommitted()) {

            boolean isProjectRight = checkProjectName(target);

            String msg = "";

            if (!isProjectRight) {
                msg = "缺少项目名，正确地址应为：/" + URLUtil.getProjectName() + target;
            }

            log.info("无法处理:" + target + ",建议：【" + msg + "】"+" ;请求IP:"+ip);
        }
        else if (response.getStatus() == HttpStatus.NOT_FOUND_404) {

            String msg = "";

            if (target.startsWith("/" + URLUtil.getProjectName() + "/api/")) {
                msg = "检查controller的名称和action名称是否正确，/" + URLUtil.getProjectName()
                    + "/api/{controller}/{action}";
            }
            else if (target.startsWith("/" + URLUtil.getProjectName() + "/webResource/")) {
                String webBasePath = PropertiesUnit.getValue("webBasePath");
                String filePath = webBasePath + "/" + target.replaceFirst(
                    "/" + URLUtil.getProjectName() + "/", "");
                msg = "静态资源：" + filePath + "不存在";
            }
            else {
                msg = "路径错误，路径应为:[/" + URLUtil.getProjectName() + "/api/…],[" + URLUtil
                    .getProjectName() + "/webResource/…]";
            }

            log.info("无法处理:" + target + ",建议：【" + msg + "】" +" ;请求IP:"+ip);
        }

    }

    private boolean checkProjectName(String uri) {

        String projectName = URLUtil.getProjectName();

        if (projectName == null || projectName.equals("")) {
            return true;
        }

        if (!uri.startsWith(projectName)) {
            return false;
        }

        if (uri.length() > projectName.length() && uri.charAt(projectName.length()) != '/') {
            return false;
        }

        return true;
    }

}
